package com.hjy.attendance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hjy.attendance.cache.CourseCache;
import com.hjy.attendance.cache.TeacherCache;
import com.hjy.attendance.context.IMContextHolder;
import com.hjy.attendance.dao.CourseDao;
import com.hjy.attendance.entity.*;
import com.hjy.attendance.enums.ResultEnum;
import com.hjy.attendance.exception.ApiException;
import com.hjy.attendance.service.*;
import com.hjy.attendance.util.BeanUtil;
import com.hjy.attendance.util.JwtUtil;
import com.hjy.attendance.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>标题: 课程表 Service 实现类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2020</p>
 *
 * @version: 1.0
 * @author: huangjunyu
 * @date 2020-04-18
 */
@Service
public class CourseServiceImpl extends BaseServiceImpl<CourseDao, Course> implements CourseService {
    @Autowired
    TeacherCache teacherCache;

    @Autowired
    CourseCache courseCache;

    @Autowired
    UserService userService;

    @Autowired
    StudentService studentService;

    @Autowired
    CourseDetailService courseDetailService;

    @Autowired
    AttendanceParentService attendanceParentService;

    @Autowired
    AttendanceSonService attendanceSonService;


    @Override
    public List<Map<String,Object>> getCourseListByKeyWords(String courseName, String teacherName) {
        List<Map<String,Object>> courses=courseCache.get().stream().
                filter(course -> course.getCourseName().contains(courseName.trim()))
                .map(BeanUtil::transBean2Map)
                .peek(courseMap->{
                    courseMap.put("teacherName",teacherCache.get().stream().
                            filter(teacher ->
                                    courseMap.get("teacherId").toString().equalsIgnoreCase(teacher.getGuid())).findFirst().get().getName());
                    teacherCache.get().stream().filter(data->courseMap.get("createOperator").toString().equalsIgnoreCase(data.getGuid())).findFirst().orElseGet(()->{
                        Optional.<User>ofNullable(userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName,courseMap.get("createOperator").toString()))).ifPresent(param->{
                            courseMap.put("createOperator",param.getUserName());
                        });
                        return null;
                    });
                })
                .filter(couseMap->couseMap.get("teacherName").toString().contains(teacherName))
                .collect(Collectors.toList());

        return courses;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(Map<String, Object> requestMap) throws ApiException {
        final String userId=JwtUtil.decode(IMContextHolder.get("token"));
        User user=Optional.ofNullable(userService.getById(userId)).orElseThrow(()->new ApiException(ResultEnum.CUSTOMFAILURE,"当前操作用户已不存在"));
        String courseName=requestMap.get("courseName").toString();
        Date createTime= new Date(Long.parseLong(requestMap.get("createTime").toString()));
        String fitMajor=requestMap.get("fitMajor").toString();
        String teacherId=requestMap.get("teacherId").toString();
        Integer validFlag=Integer.valueOf(requestMap.get("validFlag").toString());
        byte[] content=null;
        try {
            content=requestMap.get("content").toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //判断课程名是否已经存在
        Optional<Course> optionalCourse=courseCache.get().stream().filter(data->{
            return (data.getCourseName().equals(courseName));
        }).findFirst();
        if (optionalCourse.isPresent()){
            throw new ApiException(ResultEnum.CUSTOMFAILURE,"该课程名字已经存在");
        }
        //判断通过，开始插入
        Course course=Course.builder()
                .courseName(courseName)
                .courseNo(UUID.randomUUID().toString())
                .createOperator(userId)
                .createTime(createTime)
                .teacherId(teacherId)
                .updateTime(createTime)
                .build();
        insert(course);
        //插入细表
        CourseDetail courseDetail=CourseDetail.builder()
                .courseNo(course.getCourseNo())
                .content(content)
                .createTime(course.getCreateTime())
                .fitMajor(fitMajor)
                .title(courseName)
                .updateTime(course.getUpdateTime())
                .validFlag(validFlag).build();

        courseDetailService.insert(courseDetail);
        courseCache.clear();


    }

    @Override
    @Transactional
    public void deleteAllByCourseNo(String courseNo) throws ApiException {
        deleteById(courseNo);
        this.courseDetailService.deleteById(courseNo);
        List<AttendanceParent> attendanceParents=this.attendanceParentService.list(new QueryWrapper<AttendanceParent>(AttendanceParent.builder().courseNo(courseNo).build()));
        attendanceParents.stream().forEach(data->{
            attendanceSonService.delete(new QueryWrapper<AttendanceSon>(AttendanceSon.builder().attentanceParentId(data.getGuid()).build()));
        });
        this.attendanceParentService.deleteBatch(attendanceParents,attendanceParents.size());
        courseCache.clear();
    }

}
